﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace FTI
{
    public partial class Utility
    {
        public static string[] Operators = new string[] { "=", ">=", "<=", "<>", "!=", "<", ">", "~" };

        public static void WriteToCSVStream(TextWriter stream, DataTable dt, bool header, bool quoteall)
        {
            if (header)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    WriteCSVItem(stream, dt.Columns[i].Caption, quoteall);
                    if (i < dt.Columns.Count - 1)
                        stream.Write(',');
                    else
                        stream.Write('\n');
                }
            }
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    WriteCSVItem(stream, row[i], quoteall);
                    if (i < dt.Columns.Count - 1)
                        stream.Write(',');
                    else
                        stream.Write('\n');
                }
            }
        }

        public static void WriteCSVItem(TextWriter stream, object item, bool quoteall)
        {
            if (item == null)
                return;
            string s = item.ToString().Trim();
            if (quoteall || s.IndexOfAny("\",\x0A\x0D ".ToCharArray()) > -1)
                stream.Write("\"" + s.Replace("\"", "\"\"") + "\"");
            else
                stream.Write(s);
        }
    }
}
